from django.contrib.auth import authenticate, login
from django.views import View
from .forms import LoginForm, CatForm
from django.contrib.auth import logout
from .models import Cat, Apply, Donate, Person, Site
from django.shortcuts import render, redirect, get_object_or_404
from django.db import connection

def logout_view(request):
    logout(request)
    return redirect('login')  # 重定向到登录页面

class LoginView(View):
    def get(self, request):
        if request.user.is_authenticated:
            return redirect('home')
        form = LoginForm()
        return render(request, 'accounts/login.html', {'form': form})

    def post(self, request):
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
        return render(request, 'accounts/login.html', {'form': form})

def home(request):
    return render(request, 'accounts/home.html')

def cat_list(request):
    # 使用原生SQL联表查询
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT c.*, s.sname as site_name 
            FROM cat c 
            LEFT JOIN site s ON c.siteid = s.siteid
        """)
        columns = [col[0] for col in cursor.description]
        cats = [dict(zip(columns, row)) for row in cursor.fetchall()]
    return render(request, 'accounts/cat.html', {'cats': cats})


def cat_create(request):
    if request.method == 'POST':
        form = CatForm(request.POST)
        if form.is_valid():
            # 手动构建SQL插入语句
            with connection.cursor() as cursor:
                cursor.execute("""
                    INSERT INTO cat (cname, cgender, month, status, siteid, description)
                    VALUES (%s, %s, %s, %s, %s, %s)
                """, [
                    form.cleaned_data['cname'],
                    form.cleaned_data['cgender'],
                    form.cleaned_data['month'],
                    form.cleaned_data['status'],
                    form.cleaned_data['siteid'],
                    form.cleaned_data['description'],
                ])
            return redirect('cat_list')
    else:
        form = CatForm()
    # 明确传递 is_edit=False
    return render(request, 'accounts/cat_form.html', {
        'form': form,
        'is_edit': False
    })


def cat_update(request, pk):
    if request.method == 'POST':
        form = CatForm(request.POST)
        if form.is_valid():
            with connection.cursor() as cursor:
                cursor.execute("""
                    UPDATE cat 
                    SET cname = %s, cgender = %s, month = %s, status = %s, siteid = %s, description = %s 
                    WHERE catid = %s
                """, [
                    form.cleaned_data['cname'],
                    form.cleaned_data['cgender'],
                    form.cleaned_data['month'],
                    form.cleaned_data['status'],
                    form.cleaned_data['siteid'],
                    form.cleaned_data['description'],
                    pk
                ])
            return redirect('cat_list')
    else:
        # 获取现有数据填充表单
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM cat WHERE catid = %s", [pk])
            cat_data = cursor.fetchone()
            if cat_data:
                form = CatForm(initial={
                    'cname': cat_data[1],
                    'cgender': cat_data[2],
                    'month': cat_data[3],
                    'status': cat_data[4],
                    'siteid': cat_data[5],
                    'description': cat_data[6],
                })
            else:
                return redirect('cat_list')
    return render(request, 'accounts/cat_form.html', {
        'form': form,
        'is_edit': True,
        'cat_id': pk
    })


def cat_delete(request, pk):
    if request.method == 'POST':
        with connection.cursor() as cursor:
            cursor.execute("DELETE FROM cat WHERE catid = %s", [pk])
        return redirect('cat_list')

    # 获取猫咪信息用于确认页面显示
    with connection.cursor() as cursor:
        cursor.execute("SELECT name FROM cat WHERE catid = %s", [pk])
        cat_name = cursor.fetchone()[0] if cursor.rowcount > 0 else None

    if not cat_name:
        return redirect('cat_list')

    return render(request, 'accounts/cat_confirm_delete.html', {'cat_name': cat_name})





def apply_list(request):
    # 使用prefetch_related优化关联查询
    applications = Apply.objects.all()
    return render(request, 'accounts/apply.html', {'applications': applications})

def donate_list(request):
    donations = Donate.objects.all()
    return render(request, 'accounts/donate.html', {'donations': donations})

def person_list(request):
    persons = Person.objects.all()
    return render(request, 'accounts/person.html', {'persons': persons})

def site_list(request):
    sites = Site.objects.all()
    return render(request, 'accounts/site.html', {'sites': sites})